package com.aiguigu.cas;


import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

class number{
    private int num;

    public int getNum() {
        return num;
    }

    public synchronized void setNum() {
        ++num;
    }

    //=====================================
    AtomicInteger atomicInteger=new AtomicInteger();

    public AtomicInteger getAtomicInteger() {
        return atomicInteger;
    }

    public void setAtomicInteger() {
        atomicInteger.getAndIncrement();
    }
}

//100个线程，每个线程加100次，求最后的number值
public class CASDemo {
    public static void main(String[] args) throws InterruptedException {
        number number = new number();
        CountDownLatch countDownLatch = new CountDownLatch(100);
        for (int i = 0; i < 100; i++) {
            new Thread(()->{
                for (int j = 0; j < 100; j++) {
                    number.setNum();
                    number.setAtomicInteger();
                }
                countDownLatch.countDown();
            },String.valueOf(i)).start();
        }

        countDownLatch.await();
        System.out.println(Thread.currentThread().getName()+"\t"+"获得最后结果： "+number.getNum());
        System.out.println(Thread.currentThread().getName()+"\t"+"获得最后结果： "+number.getAtomicInteger());
    }


}
